package com.why.utils;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.why.enums.ErrorEnum;
import com.why.exception.RpcException;
import lombok.extern.slf4j.Slf4j;


import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;


@Slf4j
public class NacosUtil {


    private static final NamingService namingService;
    //获取到的服务的名字
    private static final Set<String> serviceNames = new HashSet<>();
    //去注册服务，
    private static InetSocketAddress address;

    private static final String SERVER_ADDR = "127.0.0.1:8848";

    static {
        namingService = getNacosNamingService();
    }

    /**
     * 得到注册中心。
     * @return
     */
    public static NamingService getNacosNamingService() {
        try {
            return NamingFactory.createNamingService(SERVER_ADDR);
        } catch (NacosException e) {
            log.error("使用nacosUtils注册服务失败！");
            log.error("连接到Nacos时有错误发生: ", e);
            throw new RpcException(ErrorEnum.CONNECT_NACOS_ERROR);
        }
    }

    /**
     * 注册服务
     * @param serviceName
     * @param address
     * @throws NacosException
     */
    public static void registerService(String serviceName, InetSocketAddress address) throws NacosException {
        namingService.registerInstance(serviceName, address.getHostName(), address.getPort());
        NacosUtil.address = address;
        serviceNames.add(serviceName);

    }

    /**
     * 得到所有的符合要求的所有服务
     * @param serviceName
     * @return
     * @throws NacosException
     */
    public static List<Instance> getAllInstances(String serviceName) throws NacosException {
        return namingService.getAllInstances(serviceName);
    }

    /**
     * 当服务提供者正常退出的时候，会去注册中心清除自己的信息
     */
    public static void clearRegistry() {
        if(!serviceNames.isEmpty() && address != null) {
            String host = address.getHostName();
            int port = address.getPort();
            Iterator<String> iterator = serviceNames.iterator();
            while(iterator.hasNext()) {
                String serviceName = iterator.next();
                try {
                    namingService.deregisterInstance(serviceName, host, port);
                    iterator.remove();
                } catch (NacosException e) {
                    log.error("注销服务 {} 失败", serviceName, e);
                }
            }
        }
    }
}